//
//  RecommendCell.m
//  Mooker
//
//  Created by Jikui Peng on 12-8-14.
//  Copyright (c) 2012年 banma. All rights reserved.
//

#import "RecommendCell.h"
#import <QuartzCore/QuartzCore.h>

#define kDefaultTimeInterval  10.0f
#define kDefaultPixel         15


#define COLOR_IMAGE_DEFAULT_BG        COLOR_RGB(221, 221, 221)
#define COLOR_IMAGE_DEFAULT_BG_NIGHT  COLOR_RGB(61, 61, 61)

@interface RecommendCell()

@property (nonatomic, readonly) CGFloat picCenterX;
@property (nonatomic, readonly) CGFloat picCenterY;

@end

@implementation RecommendCell
@synthesize imageView = _imageView;
@synthesize object = _object;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        [self addSubview:self.imageView];
        
    }
    return self;
}

- (void)layoutSubviews{
    [self.imageView setFrame:self.bounds];
    [self resizeImageView];
}

- (void)showRecommendContent:(NSString *)imageUrl
{
    self.imageView.contentMode = UIViewContentModeCenter;
    if (imageUrl==nil || [imageUrl isEqualToString:@""]) {
        self.imageView.image = IMGNAMED(@"defaul_cover_4.jpg");
        return;
    }

    __block RecommendCell *cell = self;
    __block UIImageView *imageView = self.imageView;
    [self.imageView setImageWithURL:[NSURL URLWithString:imageUrl]
                   placeholderImage:IMGNAMED(@"defaul_cover_4.jpg")
                          completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                              if (error == nil) {
                                  
                                  [cell resizeImageView];
                                  imageView.contentMode = UIViewContentModeScaleAspectFill;
                              }
        
    }];
}


- (void)setObject:(CuzyTBKItem *)object{
    _object = object;
    [self showRecommendContent:_object.itemImageURLString];
    
}

- (void)startAnimation
{
    if (self.imageView.image.size.height<self.bounds.size.height && self.imageView.image.size.width<self.bounds.size.width) {
        if ([self.delegate respondsToSelector:@selector(pathAnimationDidFinishedWithImageView:)]) {
            [self.delegate pathAnimationDidFinishedWithImageView:self.imageView];
        }
        return;
    }
    
    CGMutablePathRef path = CGPathCreateMutable();
    //指定初始位置
    CGPathMoveToPoint(path, NULL, self.imageView.layer.position.x, self.imageView.layer.position.y);
    
    //设置移动直线
    CGFloat  v = (self.imageView.frame.size.height - self.bounds.size.height)/2;
    CGFloat  h = (self.imageView.frame.size.width - self.bounds.size.width)/2;
    
    //若缩放后的图片的宽/高，与视图大小在一定像素范围内，则不用做移动动画
    CGFloat  pathY = v<5?0:v;
    CGFloat  pathX = h<5?0:h;
    if (pathY != 0 || pathX != 0) {
        CGPathAddLineToPoint(path, NULL, self.picCenterX+pathX, self.picCenterY+pathY);
        CGPathAddLineToPoint(path, NULL, self.picCenterX, self.picCenterY);
        CGPathAddLineToPoint(path, NULL, self.picCenterX-pathX, self.picCenterY-pathY);
        CGPathAddLineToPoint(path, NULL, self.picCenterX, self.picCenterY);
    }
    
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [pathAnimation setPath:path];
    CGFloat  timeInterval;
    if (pathX == 0) {
        timeInterval = (pathY/kDefaultPixel < kDefaultTimeInterval)?kDefaultTimeInterval:pathY/kDefaultPixel;
    }else{
        timeInterval = (pathX/kDefaultPixel < kDefaultTimeInterval)?kDefaultTimeInterval:pathX/kDefaultPixel;
    }
    pathAnimation.duration = timeInterval * 3;
    [pathAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = YES;
    pathAnimation.delegate = self;
    [pathAnimation setValue:@"pathAnim" forKey:@"pathAnim"];
    
    CFRelease(path);
    [self.imageView.layer addAnimation:pathAnimation forKey:@"pathAnim"];
    // 动画结束后设置回中心位置
    self.imageView.layer.position = CGPointMake(self.picCenterX, self.picCenterY);
}

- (void)stopAnimation
{
    // 记录现在动画的位置
    CGPoint point = [(CALayer *)[self.imageView.layer presentationLayer] position];
    [self.imageView.layer removeAllAnimations];
    self.imageView.layer.position = point;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    NSString  *path = [anim valueForKey:@"pathAnim"];
    if ([path isEqualToString:@"pathAnim"]) {
        if ([self.delegate respondsToSelector:@selector(pathAnimationDidFinishedWithImageView:)]) {
            [self.delegate pathAnimationDidFinishedWithImageView:self.imageView];
        }
    }
}

- (void)resizeImageView{
    
    CGSize size = self.imageView.image.size;
    
    CGFloat ratio1 = self.bounds.size.width/size.width;
    CGFloat ratio2 = self.bounds.size.height/size.height;
    
    if (ratio1 > ratio2) {
        size.width = self.bounds.size.width;
        size.height = size.height*ratio1;
    } else {
        size.width = size.width*ratio2;
        size.height = self.bounds.size.height;
    }
    
    self.imageView.frame = CGRectMake(0, 0, size.width, size.height);
    self.imageView.center = CGPointMake(self.picCenterX, self.picCenterY);
    self.imageView.layer.position = CGPointMake(self.picCenterX, self.picCenterY);
}

#pragma mark - BUImageViewDelegate Method

#pragma mark - getter
- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.backgroundColor = COLOR_IMAGE_DEFAULT_BG;
        _imageView.clipsToBounds = YES;
        _imageView.contentMode = UIViewContentModeCenter;
        
        _imageView.image = IMGNAMED(@"defaul_cover_4.jpg");
        [self addSubview:_imageView];
    }
    return _imageView;
}

- (CGFloat)picCenterX
{
    return self.bounds.size.width/2;
}

- (CGFloat)picCenterY
{
    return self.bounds.size.height/2;
}

@end


